package com.app.dataprovider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.app.constant.Constant;
import com.app.model.Word;

public class DataProvider {
	// map of book - list word
	private Map<String, List<Word>> dataMap = new HashMap<>();
	private static DataProvider THIS;
	
	private DataProvider() {
		setupData();
	}
	
	private String[] testData = {"Hello"};
	private void setupData() {
		List<Word> lstWord = new ArrayList<>(10);
		
		for (int i = 0; i < testData.length; i++) {
			Word w = new Word();
			lstWord.add(w);
			
			w.setId(i);
			w.setWord(testData[i]);
			w.setDescription("");
			w.setImagePath("");
		}
		dataMap.put(Constant.BOOK_DEFAULT, lstWord);
	}
	
	public static DataProvider getInstance() {
		if (THIS == null) {
			THIS = new DataProvider();
		}
		
		return THIS;
	}
	
	public List<Word> getBookSet(String name) {
		List<Word> bookSet = dataMap.get(name);
		
		return bookSet;
	}
	
	/**
	 * Add a work into a specified book.
	 * If the book is not existed and {createBookIfNotExist} is true,
	 * book is created.
	 * 
	 * @param bookName
	 * @param w
	 * @param createBookIfNotExist 
	 */
	public void addWord(String bookName, Word w, boolean createBookIfNotExist) {
		if (w == null || w.getWord().isEmpty()) {
			return;
		}
		
		List<Word> book = dataMap.get(bookName);
		if (book == null) {
			if (createBookIfNotExist) {
				book = new ArrayList<>(10);
				dataMap.put(bookName, book);
			}
		}
		
		if (book != null) {
			w.setId(book.size());
			book.add(w);
		}
	}
	
	public void deleteWord(String bookName, long id) {
		if (bookName == null || bookName.isEmpty()) {
			return;
		}
		
		List<Word> book = dataMap.get(bookName);
		if (book!= null && !book.isEmpty()) {
			for (int i = 0; i < book.size(); i++) {
				Word w = book.get(i);
				if (w.getId() == id) {
					book.remove(i);
					return;
				}
			}
		}
	}
}
